#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : chat_model 
# @File    : home.py
# @IDE     : PyCharm 
# @Author  :ZH
# @Time    : 2025/1/9 14:11
import datetime

from fastapi import Security

from apps import logic, model_utils
from apps.api.v1.home_api import home_router
from apps.models import User
from apps.utils import get_current_user


@home_router.post('/update_log', name='版本更新日志')
async def home_update_log(
        *,
        user: User = Security(get_current_user)
):
    update_log = await logic.update_log_logic.get_new_log()
    return {
        'code': 0,
        "message": "成功",
        "data": "" if not update_log else update_log.update_log
    }


@home_router.get('/data', name='获取首页统计数据')
async def home_data(
        *,
        user: User = Security(get_current_user)
):
    # 统计当前的注册人数
    count, _ = await logic.user_logic.user_list(page_size=1)
    # 统计最近一个月消耗记录
    chat_all = await logic.dialogue_logic.home_dialogue()
    # 获取当前日期
    today = datetime.datetime.now()
    key_list = [(today - datetime.timedelta(days=i)).strftime('%Y-%m-%d') for i in range(30)][::-1]
    # 根据天进行分组统计
    tokens_count = {i: 0 for i in key_list}
    for i in chat_all:
        if not i.answer:
            continue
        usage_tokens = i.usage_tokens if i.usage_tokens else len(i.answer)
        if i.create_date.strftime('%Y-%m-%d') not in tokens_count:
            tokens_count[i.create_date.strftime('%Y-%m-%d')] = usage_tokens
        else:
            tokens_count[i.create_date.strftime('%Y-%m-%d')] += usage_tokens

    return {
        'code': 0,
        "message": "成功",
        "data": {
            'user_count': count,
            "tokens": {
                "key": list(tokens_count.keys()),
                "value": list(tokens_count.values())
            }
        }
    }

    pass
